package com.meta.pic.util

import android.content.Context
import android.util.AttributeSet
import android.widget.FrameLayout

/**
 * @author luwenjie on 2019-06-14 14:18:07
 * 按宽高比来 布局
 */
class RatioLayout @JvmOverloads constructor(
    context: Context, attr: AttributeSet? = null,
    def: Int = 0
) : FrameLayout(context, attr, def) {

    var whRatio = 1F

    // 以宽为基础，计算高
    var isBaseInWidth = true


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {

        setMeasuredDimension(
            getDefaultSize(0, widthMeasureSpec),
            getDefaultSize(0, heightMeasureSpec)
        );
        val childWidthSize = measuredWidth
        val childHeightSize = measuredHeight

        if (isBaseInWidth) {
            val h =
                MeasureSpec.makeMeasureSpec((childWidthSize / whRatio).toInt(), MeasureSpec.EXACTLY)
            super.onMeasure(widthMeasureSpec, h)
        } else {
            val w = MeasureSpec.makeMeasureSpec(
                (childHeightSize * whRatio).toInt(),
                MeasureSpec.EXACTLY
            )
            super.onMeasure(w, heightMeasureSpec)
        }

    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
    }


    companion object {
        private const val TAG = "RatioLayout"
    }
}